<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>保留 or 删除元素</title>
</head>
<body>
<div id="change" class="change">
    <h1 data-if="isReserve" style="background-color: green">Hello， World！</h1>
    <h1 data-else style="background-color: red">Hello， World！</h1>
</div>

<script !src="">
    let isReserve = false
    let retain = isReserve
    let status = false

    let elements = document.querySelectorAll("#change h1");

    for (let i = 0; i < elements.length; i++) {
        let attributeNames = elements[i].getAttributeNames();

        for (let j = 0; j < attributeNames.length; j++) {
            // console.log(elements[i].getAttribute(attributeNames[j]));
            if (attributeNames[j] === 'data-if') {
                if (eval(elements[i].getAttribute(attributeNames[j]))) {
                    elements[i].removeAttribute(attributeNames[j])
                } else {
                    elements[i].remove()
                    status = true

                }
            }
            else if (attributeNames[j] === 'data-else'){
                if (retain) {
                    elements[i].remove()
                }

                if (status){
                    elements[i].removeAttribute(attributeNames[j])
                }
            }
        }
    }
</script>
</body>
</html>